package com.lkm.app_ui.m.Imple.fun.upapp;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.event.OnApkDownEvent;
import com.lkm.app_ui.event.RequestInstallApkEvent;
import com.lkm.app_ui.help.WindowViewHelp;
import com.lkm.comlib.Config;
import com.lkm.comlib.down.DownApkHelp;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.entity.ResponEntityAbs;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.rockchip.rkapi.RKapi;

import java.util.List;



public class CheckUpdateUITask extends TaskAdapter<Void, Void, Void> {

    public static String getTaskId() {
        return CheckUpdateUITask.class.getName();
    }

    private boolean isShowUI = false;
    private ActivityManager activityManager;
    private String packageName;

    public CheckUpdateUITask(boolean isShowUI) {
        super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), getTaskId(), AppConst.getTaskManager2());
        this.isShowUI = isShowUI;
    }


    @Override
    public void doExecuting(Void param) {
        super.doExecuting(param);
        activityManager = (ActivityManager) AppConst.getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        packageName = AppConst.getApplication().getPackageName();
        loopUI();


        CheckUpdateTask task = new CheckUpdateTask();
        task.action();
        task.setParam(null);
        task.execTask();
        task.addBackCall(checkUpBC);

        upUI();
    }

    private void loopUI() {
        if (  getIsContinue())
            mTaskExecutor.executeOnDispatchDelayed(new Runnable() {
                @Override
                public void run() {
                    if (  getIsContinue()) {
                        if (appOnForeground()) {

                            goneUI(false);
                        } else {

                            goneUI(true);
                        }
                        loopUI();

                    }
                }
            }, 1 * 1000);
    }

















    @Override
    public boolean onInterceptEnd(boolean isCancel, Void result) {

        closeUI();
        return super.onInterceptEnd(isCancel, result);
    }

    private BackCallAdapter<Void, ResponEntityAbs<CheckUpdateBo>> checkUpBC = new BackCallAdapter<Void, ResponEntityAbs<CheckUpdateBo>>() {

        @Override
        protected void onEnd(Task<?, Void, ResponEntityAbs<CheckUpdateBo>> task, ResponEntityAbs<CheckUpdateBo> result, boolean isCancel) {
            super.onEnd(task, result, isCancel);
            if (!isCancel && result.isSuccess()) {
                CheckUpdateBo checkUpdateBo = result.getData();
                if (checkUpdateBo.hasUp) {
                    Activity activity = BaseFragmentActivity.getLastActivity();
                    if (activity == null) return;

                    if (checkUpdateBo.isAuto) {
                        new MDownApkHelp(activity).downAPK(activity, checkUpdateBo.downUrl, Config.getApkFileCache(activity), checkUpdateBo.version + ".apk");

                    } else {
                        ViewUIHelp.showAlertDialog(activity, checkUpdateBo.tips, new Runnable() {
                            @Override
                            public void run() {
                                new MDownApkHelp(activity).downAPK(activity, checkUpdateBo.downUrl, Config.getApkFileCache(activity), checkUpdateBo.version + ".apk");

                                ViewUIHelp.showTipsLong(activity, "已经在后台下载");

                            }
                        }, null);
                    }
                }else{
                    CheckUpdateUITask.this.complete(null);
                }
            } else {
                CheckUpdateUITask.this.cancel();
            }

        }

    };

    private class MDownApkHelp extends DownApkHelp {
        public MDownApkHelp(Context context) {
            super(context);
        }

        @Override
        public void onDownloadFail(String fileUrl, boolean isNotStore) {
            super.onDownloadFail(fileUrl, isNotStore);
            onDownloadEnd();
            LinkBus.sendBroadcast(new OnApkDownEvent(OnApkDownEvent.status_fail));
        }


        @Override
        public void onDownloadSucceed(String fileUrl, String savePath) {
            super.onDownloadSucceed(fileUrl, savePath);
            onDownloadEnd();
            LinkBus.sendBroadcast(new OnApkDownEvent(OnApkDownEvent.status_success));
        }

        @Override
        public void downAPK(Context c, String apkurl, String saveDic, String saveName) {

            LinkBus.sendBroadcast(new OnApkDownEvent(OnApkDownEvent.status_start));
            super.downAPK(c, apkurl, saveDic, saveName);

            progressUI(0);


        }

        @Override
        public void onProgressUpdate(int progre, String imageUrl, String savePath) {
            super.onProgressUpdate(progre, imageUrl, savePath);
            LinkBus.sendBroadcast(new OnApkDownEvent(progre*-1));

            progressUI(progre);

        }

        private void onDownloadEnd() {
            CheckUpdateUITask.this.complete(null);

        }

        @Override
        protected void onInstallApp(String savePath) {

            LinkBus.sendBroadcast(new RequestInstallApkEvent(savePath));






        }
    }



    private boolean appOnForeground() {
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    private View view;
    private int progress = 0;

    private void progressUI(int progress) {
        this.progress = progress;
        upUI();
    }

    private void upUI(){
        if( getIsContinue())
        mTaskExecutor.executeOnDispatch(new Runnable() {
            @Override
            public void run() {
                upUI_();
            }
        });
    }

    private void upUI_() {
        if (!isShowUI) return;

        if (view == null) {
            view = LayoutInflater.from(AppConst.getApplication()).inflate(R.layout.dialog_progress, null);
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;

            view.setLayoutParams(layoutParams);
            showView(view, AppConst.getApplication(), 0, 0);
        }
        ((TextView) view.findViewById(R.id.tv_tips)).setText("当前版本较老，已不可使用。正更新到新版本，下载apk进度%:" + progress);

    }

    private void closeUI() {
        if (view != null) {
            ViewHelp.removeParentView(view);
        }
    }

    public void showView(View view, Context mContext, int x, int y) {

        WindowManager.LayoutParams params = (WindowManager.LayoutParams) view.getLayoutParams();

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;

//            params.type = WindowManager.LayoutParams.TYPE_PHONE;


//        https://blog.csdn.net/self_study/article/details/52859790

        params.type = WindowManager.LayoutParams.TYPE_TOAST;

        params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

//        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.RGBA_8888;//android.graphics.PixelFormat.TRANSLUCENT;

        params.gravity = Gravity.LEFT | Gravity.TOP;

        params.x = x;
        params.y = y;
        WindowViewHelp.instance().getWindowManager(mContext).addView(view, params);
        view.setVisibility(View.VISIBLE);

    }

    private void goneUI(boolean isGone) {
        if (view != null) {
            view.setVisibility(isGone ? View.GONE : View.VISIBLE);
        }

    }

}
